<template>
  <div id="imageContainer"></div>
</template>

<script>
import data from "../../assets/json/李白年谱.json";
import { useStore } from "vuex";
export default {
  data() {
    return {
      data,
      time: null, // 初始化time为null
    };
  },
  setup() {
    const store = useStore();
    return { store };
  },
  methods: {
    draw(time) {
      const imageContainer = document.getElementById("imageContainer");

      imageContainer.innerHTML = "";

      const individuals =
        data[time] && data[time]["人物"] ? Object.keys(data[time]["人物"]) : [];

      if (individuals) {
        individuals.forEach((person) => {
          // 创建图片元素
          const imageDiv = document.createElement("div"); // 创建imageDiv元素
          const image = document.createElement("img");
          image.src = "picture/figureImage/" + person + ".jpg";
          // 假设图片以人物名字命名，且为jpg格式
          image.alt = person;
          // console.log(person);
          // console.log(image.src);
          // 创建人物名字元素
          const name = document.createElement("p");
          name.textContent = person;

          // 判断图片是否加载成功
          image.onload = function () {
            // 将图片和人物名字元素插入到图片容器中
            imageDiv.appendChild(image);
            imageDiv.appendChild(name);

            // 将图片容器插入到imageContainer中
            imageContainer.appendChild(imageDiv);
          };

          image.onerror = function () {
            // console.log("图片加载失败");
          };

          // 尝试加载图片
          image.src = "picture/figureImage/" + person + ".jpg";
        });
      }
    },
  },
  created() {
    this.$store.watch(
      (state) => state.time,
      (newVal) => {
        this.time = newVal;
        this.draw(this.time); // 传入this.time作为参数
      }
    );
  },
  mounted() {
    this.draw(this.time); // 传入this.time作为参数
  },
};
</script>

<style>
#imageContainer {
  display: flex;
  flex-direction: row;
}

img {
  width: 40px;
  aspect-ratio: 1/1;
  border-radius: 50%;
  margin-right: 30px;
}

</style>
